package com.example.mr5.money.main.home;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.mr5.money.R;
import com.example.mr5.money.constant.Constant;
import com.example.mr5.money.util.DatabaseHelper;
import com.example.mr5.money.util.DateUtil;
import com.example.mr5.money.view.ChartView;

import java.util.Calendar;

/**
 * Created by Mr.5
 * Date：2016/9/11.
 * Time：22:35
 */
public class HomeFragment extends Fragment {
    private TextView allMoney, allExpense, allIncome, monthIncome, monthExpense;
    private DatabaseHelper helper;
    private SQLiteDatabase db;
    private float allMyMoney;
    private float thisMonthIncome;
    private float thisMonthExpense;
    private Calendar now;
    private ChartView incomeChart, expenseChart;
    private int thisMonth;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        helper = DatabaseHelper.getDBInstance(getContext());
        db = helper.getReadableDatabase();
        helper = DatabaseHelper.getDBInstance(getContext());
        db = helper.getReadableDatabase();
        now = Calendar.getInstance();
        thisMonth = now.get(Calendar.MONTH) + 1;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(getContext(), R.layout.fragment_home, null);
        allMoney = (TextView) view.findViewById(R.id.all_money);
        allExpense = (TextView) view.findViewById(R.id.all_expense);
        allIncome = (TextView) view.findViewById(R.id.all_income);
        monthIncome = (TextView) view.findViewById(R.id.month_income_text);
        monthExpense = (TextView) view.findViewById(R.id.month_expense_text);
        monthExpense.setText((now.get(Calendar.MONTH) + 1) + "月支出");
        monthIncome.setText((now.get(Calendar.MONTH) + 1) + "月收入");
        incomeChart = (ChartView) view.findViewById(R.id.income_chart);
        expenseChart = (ChartView) view.findViewById(R.id.expense_chart);
        updateView();

        return view;
    }

    private void updateView() {
        allMoney.setText("" + allMyMoney);
        allIncome.setText("+" + thisMonthIncome);
        allExpense.setText("-" + thisMonthExpense);
    }

    private void calculate() {
        float[] incomeChartData = new float[thisMonth];
        float[] incomeChartData5 = new float[5];
        allMyMoney = 0;
        thisMonthExpense = 0;
        thisMonthIncome = 0;
        Cursor cursorIncome = db.query(Constant.DATABASE_INCOME_TABLE_NAME, null, null, null, null, null, null);
        while (cursorIncome.moveToNext()) {
            allMyMoney += cursorIncome.getFloat(cursorIncome.getColumnIndex(Constant.DATABASE_INCOME_TABLE_FIELD_HOW_MUCH));
            int indexMonth = Integer.parseInt(DateUtil.getMonthFromDate(cursorIncome.getString(cursorIncome.getColumnIndex(Constant.DATABASE_INCOME_TABLE_FIELD_DATE))));
            int indexYear = Integer.parseInt(DateUtil.getYearFromDate(cursorIncome.getString(cursorIncome.getColumnIndex(Constant.DATABASE_INCOME_TABLE_FIELD_DATE))));
            if ((now.get(Calendar.MONTH) + 1) == indexMonth) {
                if (now.get(Calendar.YEAR) == indexYear) {
                    thisMonthIncome += cursorIncome.getFloat(cursorIncome.getColumnIndex(Constant.DATABASE_INCOME_TABLE_FIELD_HOW_MUCH));
                }
            }
            if (thisMonth >= 5) {
                if (now.get(Calendar.YEAR) == indexYear) {
                    if (thisMonth - indexMonth < 5) {
                        incomeChartData5[indexMonth - thisMonth + 4] += cursorIncome.getFloat(cursorIncome.getColumnIndex(Constant.DATABASE_INCOME_TABLE_FIELD_HOW_MUCH));
                    }
                }
            } else {
                if (now.get(Calendar.YEAR) == indexYear) {
                    incomeChartData[indexMonth-1] += cursorIncome.getFloat(cursorIncome.getColumnIndex(Constant.DATABASE_INCOME_TABLE_FIELD_HOW_MUCH));
                }
            }
        }
        cursorIncome.close();

        //计算折线图数据
        String[] xData;//x轴刻度
        String[] yData = new String[5];
        String[] data;
        if (thisMonth >= 5){
            xData = new String[5];
            data = new String[5];
            for(int i = 0;i<5;i++){
                data[i] = incomeChartData5[i]+"";
            }
            for(int i = (thisMonth-4);i <= thisMonth;i++){
                xData[i-thisMonth+4] = i+"月";
            }

            float max = incomeChartData5[0];
            for(int j = 1;j<5;j++){
                if(max < incomeChartData5[j]){
                    max = incomeChartData5[j];
                }
            }
            int maxY = (int) max + 1;
            if (maxY % 4 != 0){
               maxY = maxY+4-maxY%4;
            }
            yData[0] = "";
            for(int i = 1;i<=4;i++){
                yData[i] = maxY*i/4+"";
            }
        }else {//小于五月
            xData = new String[thisMonth];
            data = new String[thisMonth];
            for(int i = 0;i<5;i++){
                data[i] = incomeChartData[i]+"";
            }
            for(int i = 1;i <= thisMonth;i++){
                xData[i-1] = i+"月";
            }

            float max = incomeChartData[0];
            for(int j = 1;j<incomeChartData.length;j++){
                if(max < incomeChartData[j]){
                    max = incomeChartData[j];
                }
            }
            int maxY = (int) max + 1;
            if (maxY % 4 != 0){
                maxY = maxY+4-maxY%4;
            }
            yData[0] = "";
            for(int i = 1;i<=4;i++){
                yData[i] = maxY*i/4+"";
            }
        }
        if (incomeChart != null) {
            incomeChart.SetInfo(
                    xData,   //X轴刻度
                   yData,   //Y轴刻度
                   data,  //数据
                    "");
        }
        calculateExpense();
    }

    private void calculateExpense(){
        float[] expenseChartData = new float[thisMonth];
        float[] expenseChartData5 = new float[5];
        Cursor cursorExpense = db.query(Constant.DATABASE_EXPENSE_TABLE_NAME, null, null, null, null, null, null);
        while (cursorExpense.moveToNext()) {
            allMyMoney -= cursorExpense.getFloat(cursorExpense.getColumnIndex(Constant.DATABASE_EXPENSE_TABLE_FIELD_HOW_MUCH));
            int indexMonth = Integer.parseInt(DateUtil.getMonthFromDate(cursorExpense.getString(cursorExpense.getColumnIndex(Constant.DATABASE_EXPENSE_TABLE_FIELD_DATE))));
            int indexYear = Integer.parseInt(DateUtil.getYearFromDate(cursorExpense.getString(cursorExpense.getColumnIndex(Constant.DATABASE_EXPENSE_TABLE_FIELD_DATE))));

            if ((now.get(Calendar.MONTH) + 1) == indexMonth) {
                if (now.get(Calendar.YEAR) == indexYear) {
                    thisMonthExpense += cursorExpense.getFloat(cursorExpense.getColumnIndex(Constant.DATABASE_EXPENSE_TABLE_FIELD_HOW_MUCH));
                }
            }

            if (thisMonth >= 5) {
                if (now.get(Calendar.YEAR) == indexYear) {
                    if (thisMonth - indexMonth < 5) {
                        expenseChartData5[indexMonth - thisMonth + 4] += cursorExpense.getFloat(cursorExpense.getColumnIndex(Constant.DATABASE_EXPENSE_TABLE_FIELD_HOW_MUCH));
                    }
                }
            } else {
                if (now.get(Calendar.YEAR) == indexYear) {
                    expenseChartData[indexMonth-1] += cursorExpense.getFloat(cursorExpense.getColumnIndex(Constant.DATABASE_EXPENSE_TABLE_FIELD_HOW_MUCH));
                }
            }
        }
        cursorExpense.close();

        //计算折线图数据
        String[] xData;//x轴刻度
        String[] yData = new String[5];
        String[] data;
        if (thisMonth >= 5){
            xData = new String[5];
            data = new String[5];
            for(int i = 0;i<5;i++){
                data[i] = expenseChartData5[i]+"";
            }
            for(int i = (thisMonth-4);i <= thisMonth;i++){
                xData[i-thisMonth+4] = i+"月";
            }

            float max = expenseChartData5[0];
            for(int j = 1;j<5;j++){
                if(max < expenseChartData5[j]){
                    max = expenseChartData5[j];
                }
            }
            int maxY = (int) max + 1;
            if (maxY % 4 != 0){
                maxY = maxY+4-maxY%4;
            }
            yData[0] = "";
            for(int i = 1;i<=4;i++){
                yData[i] = maxY*i/4+"";
            }
        }else {//小于五月
            xData = new String[thisMonth];
            data = new String[thisMonth];
            for(int i = 0;i<5;i++){
                data[i] = expenseChartData[i]+"";
            }
            for(int i = 1;i <= thisMonth;i++){
                xData[i-1] = i+"月";
            }

            float max = expenseChartData[0];
            for(int j = 1;j<expenseChartData.length;j++){
                if(max < expenseChartData[j]){
                    max = expenseChartData[j];
                }
            }
            int maxY = (int) max + 1;
            if (maxY % 4 != 0){
                maxY = maxY+4-maxY%4;
            }
            yData[0] = "";
            for(int i = 1;i<=4;i++){
                yData[i] = maxY*i/4+"";
            }
        }
        if (expenseChart != null) {
            expenseChart.SetInfo(
                    xData,   //X轴刻度
                    yData,   //Y轴刻度
                    data,  //数据
                    "");
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        calculate();
        updateView();
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(Constant.TAG, "HomeFragment onPause");
    }
}
